package com.dycn.util;

import org.apache.shiro.crypto.hash.SimpleHash;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    /**
     * 对字符串md5加密(小写+字母)
     *
     * @param str 传入要加密的字符串
     * @return  MD5加密后的字符串
     */
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String getPassMD5(String str) {
        return  getMD5(str+UserConfigUtil.SALE);
    }

    //两次md5并且加
    public static String get2MD5(String str) {
        String pass=getMD5(str);
        return  getPassMD5(pass);
    }

    public  static  String getHtMd5(String pass){
        String hashAlgorithmName = "MD5";
        String credentials = "123456";
        int hashIterations = 2;
        SimpleHash obj = new SimpleHash(hashAlgorithmName, pass, null, hashIterations);
//		obj = new SimpleHash(hashAlgorithmName, credentials, null, hashIterations);
//        Object obj1 = new HashedCredentialsMatcher(hashAlgorithmName, credentials, null, hashIterations);
        return obj.toString();
    }

    public static String sign(String content) {
        // 获取信息摘要 - 参数字典排序后字符串
        try {
            // 指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("md5");//sun.security.provider.SHA@74c6fd6e //sun.security.provider.MD2@4e2c390c
            digest.update(content.getBytes("utf-8"));
            // 获取字节数组
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }



    public static void main(String[] args) {
        System.out.println(getHtMd5("123456789"));
    }
}
